package com.jianghu;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.jianghu.helpers.AsyncImageLoader;
import com.jianghu.helpers.AsyncImageLoader.ImageCallback;
import com.jianghu.helpers.GetLineFromtxt;
import com.jianghu.helpers.TrendsShow;
import com.jianghu.helpers.ViewCache;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class FriendsTrendsAuto extends Activity {

	private Thread mThread;
	public Boolean surplus = true;
	LinearLayout loadingLayout=null;
	ProgressBar progressBar;
	private ListView listView;
	private LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);
	private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.FILL_PARENT,
			LinearLayout.LayoutParams.FILL_PARENT);
	public Context context = FriendsTrendsAuto.this;

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				update();
				break;
			}
			super.handleMessage(msg);
		}

		void update() {
			// Connect Server for new trends,test by toast
			Toast.makeText(FriendsTrendsAuto.this, "有新动态，请点击刷新获取!",
					Toast.LENGTH_LONG).show();
		}
	};
	Timer timer = new Timer();
	TimerTask task = new TimerTask() {
		public void run() {

			Message message = new Message();
			message.what = 1;
			handler.sendMessage(message);
		}
	};
	DownloadMore downloadMore=null;
	ProgressBar listviewBar;
	List<TrendsShow> dataArray=null;
	ImageAndTextListAdapter listItemAdapter=null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friendtrends);
		listviewBar=(ProgressBar)findViewById(R.id.proOfFriendstrends);
		timer.schedule(task, 1000 * 30, 1000 * 30);
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.HORIZONTAL);
		progressBar = new ProgressBar(this);
		progressBar.setPadding(0, 0, 15, 0);
		layout.addView(progressBar, mLayoutParams);
		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);
		layout.addView(textView, FFlayoutParams);
		layout.setGravity(Gravity.CENTER);
		loadingLayout = new LinearLayout(this);
		loadingLayout.addView(layout, mLayoutParams);
		loadingLayout.setGravity(Gravity.CENTER);

		ImageButton home = (ImageButton) findViewById(R.id.homebuttonofusertrends);
		home.setOnClickListener(new homeClickListener());

		ImageButton refresh = (ImageButton) findViewById(R.id.refreshbuttonofusertrends);
		refresh.setOnClickListener(new refreshClickListener());

		listView = (ListView) findViewById(R.id.listviewOfFriendstrends);
		dataArray = new ArrayList<TrendsShow>();
		listView.addFooterView(loadingLayout);
		listView.setCacheColorHint(0);
		downloadMore=new DownloadMore();
		downloadMore.execute((Void)null);
//		for (int i = 0; i < 20; i++) {
//
//			String str = GetLineFromtxt.readAppointedLineNumber(this, i + 1);
//			if (str == null) {
//				surplus = false;
//				break;
//			}
//			String imageUrl = "http://www.touxiang.cn/downimage/20061119100612/20061119100612(6)_200611191006126.jpg";
//			String username = "时尚英语";
//			String time = i + "小时前";
//			String contents = str;
//			TrendsShow trendsShow = new TrendsShow(imageUrl, username, time,
//					contents);
//			dataArray.add(trendsShow);
//		}

//		listItemAdapter = new ImageAndTextListAdapter(
//				this, dataArray, listView);
//		listView.setAdapter(listItemAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				if (downloadMore!=null&&downloadMore.getStatus()==AsyncTask.Status.RUNNING) {
					return;
					//downloadMore.cancel(true);
				}
//				if (mThread != null && mThread.isAlive()) {
//					Log.v("return", mThread.isAlive()+"");
//					return;
//				}
				Intent intent = new Intent();
				intent.setClass(FriendsTrendsAuto.this, UserTrendsManual.class);
				TextView userTV = (TextView) view
						.findViewById(R.id.UserNameofFriendsTrends);
				Bundle bundle = new Bundle();
				bundle.putString("item", userTV.getText().toString());
				bundle.putString("type", "trends");
				intent.putExtras(bundle);
				FriendsTrendsAuto.this.startActivity(intent);
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, final int totalItemCount) {
				if (firstVisibleItem + visibleItemCount == totalItemCount){
					if (downloadMore!=null&&downloadMore.getStatus()==AsyncTask.Status.RUNNING) {
						//Toast.makeText(FriendsTrendsAuto.this, "正在加载...", Toast.LENGTH_SHORT).show();
						return;
//						downloadMore=new DownloadMore();
//						downloadMore.execute((Void)null);
					}
				}
//					if (mThread == null || !mThread.isAlive()) {
//						mThread = new Thread() {
//							@Override
//							public void run() {
//								try {
//									loadRemnantListItem(totalItemCount - 1);
//									Thread.sleep(5000);
//								} catch (InterruptedException e) {
//									e.printStackTrace();
//								}
//								Message message = new Message();
//								message.what = 1;
//								handler.sendMessage(message);
//							}
//						};
//						mThread.start();
//					}

			}

			private Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case 1:
						listItemAdapter.notifyDataSetChanged();
						if (surplus == false) {
							listView.removeFooterView(loadingLayout);
						}
						break;
					default:
						break;
					}
				}
			};


		});

	}
	private void loadRemnantListItem(int totalItemCount) {
		int max = totalItemCount + 20;
		for (int i = totalItemCount; i < max; i++) {

			String str = GetLineFromtxt.readAppointedLineNumber(
					FriendsTrendsAuto.this, i + 1);
			if (str == null) {
				surplus = false;
				break;
			}
			String imageUrl = "http://t3.baidu.com/it/u=3744283480,376574923&fm=0&gp=0.jpg";
			String username = "冷笑话精选";
			String time = i + "小时前";
			String contents = str;
			TrendsShow trendsShow = new TrendsShow(imageUrl, username,
					time, contents);
			dataArray.add(trendsShow);
		}

	}
	public class ImageAndTextListAdapter extends ArrayAdapter<TrendsShow> {

		private ListView listView;
		private AsyncImageLoader asyncImageLoader;

		public ImageAndTextListAdapter(Activity activity,
				List<TrendsShow> TrendsShows, ListView listView) {
			super(activity, 0, TrendsShows);
			this.listView = listView;
			asyncImageLoader = new AsyncImageLoader();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Activity activity = (Activity) getContext();

			// Inflate the views from XML
			View rowView = convertView;
			ViewCache viewCache;
			if (rowView == null) {
				LayoutInflater inflater = activity.getLayoutInflater();
				rowView = inflater.inflate(R.layout.listview_friend_trends,
						null);
				viewCache = new ViewCache(rowView);
				rowView.setTag(viewCache);
			} else {
				viewCache = (ViewCache) rowView.getTag();
			}
			final TrendsShow TrendsShow = getItem(position);
			if (TrendsShow != null) {
				// Load the image and set it on the ImageView
				String imageUrl = TrendsShow.getImageUrl();
				ImageView imageView = viewCache.getImageView();
				imageView.setTag(imageUrl);
				Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl,
						new ImageCallback() {
							public void imageLoaded(Drawable imageDrawable,
									String imageUrl) {
								ImageView imageViewByTag = (ImageView) listView
										.findViewWithTag(imageUrl);
								if (imageViewByTag != null) {
									imageViewByTag
											.setImageDrawable(imageDrawable);
								}
							}
						});
				if (cachedImage == null) {
					imageView.setImageResource(R.drawable.usericon);
				} else {
					imageView.setImageResource(R.drawable.usericon);
					// imageView.setImageDrawable(cachedImage);
				}
				imageView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent();
						intent.setClass(context, UserTrendsManual.class);
						Bundle bundle = new Bundle();
						bundle.putString("item", TrendsShow.getusernameText());
						bundle.putString("type", "friends");
						intent.putExtras(bundle);
						context.startActivity(intent);
					}
				});
			}
			// Set the text on the TextView
			TextView textTimeView = viewCache.getTimesView();
			textTimeView.setText(TrendsShow.gettimesText());
			TextView textUserNameView = viewCache.getUserNameView();
			textUserNameView.setText(TrendsShow.getusernameText());
			TextView textCommentsView = viewCache.getCommentsView();
			textCommentsView.setText(TrendsShow.getcontentsText());
			return rowView;
		}

	}

	class homeClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			Intent intent = new Intent();
			intent.setClass(FriendsTrendsAuto.this, MainPage.class);
			FriendsTrendsAuto.this.startActivity(intent);

		}

	}
	class DownloadMore extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... arg0) {
			loadRemnantListItem(0);
//			for (int i = 0; i < 20; i++) {
//				String str = GetLineFromtxt.readAppointedLineNumber(FriendsTrendsAuto.this, i + 1);
//				if (str == null) {
//					surplus = false;
//					break;
//				}
//				String imageUrl = "http://www.touxiang.cn/downimage/20061119100612/20061119100612(6)_200611191006126.jpg";
//				String username = "时尚英语";
//				String time = i + "小时前";
//				String contents = str;
//				TrendsShow trendsShow = new TrendsShow(imageUrl, username, time,
//						contents);
//				dataArray.add(trendsShow);
//			}
			Log.v("dataarraty", dataArray.size()+" "+surplus);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			//listItemAdapter.notifyDataSetChanged();
			listItemAdapter = new ImageAndTextListAdapter(
					FriendsTrendsAuto.this, dataArray, listView);
			listView.setAdapter(listItemAdapter);
			listviewBar.setVisibility(View.INVISIBLE);
			if (surplus == false) {
				listView.removeFooterView(loadingLayout);
			}
			super.onPostExecute(result);
		}
	}
	class refreshClickListener implements OnClickListener {

		private ProgressDialog progressDialog;

		@Override
		public void onClick(View v) {
			if (timer != null) {
				timer.cancel();
				timer = null;
			}
			progressDialog = ProgressDialog.show(FriendsTrendsAuto.this,
					"刷新中..", "请稍等...", true, false);
			new Thread() {

				@Override
				public void run() {
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handlerRefresh.sendEmptyMessage(0);
				}
			}.start();
		}

		private Handler handlerRefresh = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				listView.setSelection(0);
				progressDialog.dismiss();
			}
		};

	}

	@Override
	protected void onDestroy() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		super.onDestroy();
	}

}